package chat

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/chat"
	"counter-help/admin/server/model/customer"
	"counter-help/admin/server/model/system"
	"encoding/json"
	"fmt"
	"time"
)

type ChatService struct{}

func (chatService *ChatService) SaveMessage(senderID int, receiverID int, content string) error {
	if senderID >= 1000000 {
		senderID = senderID - 1000000 + 1
	}
	// 定义一个临时结构来解析 content JSON
	var parsedContent struct {
		Content string `json:"content"`
	}

	// 解析 content 字段
	if err := json.Unmarshal([]byte(content), &parsedContent); err != nil {
		return fmt.Errorf("failed to parse content JSON: %w", err)
	}

	// 创建消息对象并保存到数据库
	message := chat.ChatMessage{
		SenderID:   senderID,
		ReceiverID: receiverID,
		Content:    parsedContent.Content, // 仅保存解析后的 content 字段
		Timestamp:  time.Now(),
	}

	return global.GVA_DB.Create(&message).Error
}

// 获取聊天记录
func (chatService *ChatService) GetChatHistory(senderID, receiverID int) ([]chat.ChatMessage, error) {
	if senderID >= 1000000 {
		senderID = senderID - 1000000 + 1
	}
	var messages []chat.ChatMessage
	err := global.GVA_DB.Where("(sender_id = ? AND receiver_id = ?) OR (sender_id = ? AND receiver_id = ?)",
		senderID, receiverID, receiverID, senderID).
		Order("timestamp ASC").Find(&messages).Error
	return messages, err
}

// 获取列表
func (chatService *ChatService) GetChatListHistory(receiverID int) ([]map[string]interface{}, error) {
	// 定义结构体来存储查询结果
	type ChatSummary struct {
		SenderID    int
		Content     string
		Timestamp   time.Time
		UnreadCount int // 添加未读消息计数
	}

	var summaries []ChatSummary

	// 子查询：获取每个 sender_id 的最新消息的 timestamp
	latestTimestampSubQuery := global.GVA_DB.Table("chat_messages").
		Select("sender_id, MAX(timestamp) as max_timestamp").
		Where("receiver_id = ?", receiverID).
		Group("sender_id")

	// 子查询：获取未读消息的计数
	unreadCountSubQuery := global.GVA_DB.Table("chat_messages").
		Select("sender_id, COUNT(*) as unread_count").
		Where("receiver_id = ? AND is_read = ?", receiverID, false).
		Group("sender_id")

	// 主查询：连接最新消息和未读计数
	err := global.GVA_DB.Table("chat_messages AS cm").
		Select("cm.sender_id, cm.content, cm.timestamp, COALESCE(uc.unread_count, 0) AS unread_count").
		Joins("JOIN (?) AS lt ON cm.sender_id = lt.sender_id AND cm.timestamp = lt.max_timestamp", latestTimestampSubQuery).
		Joins("LEFT JOIN (?) AS uc ON cm.sender_id = uc.sender_id", unreadCountSubQuery).
		Scan(&summaries).Error
	if err != nil {
		return nil, fmt.Errorf("failed to get chat history summaries: %w", err)
	}

	// 根据 sender_id 查询用户信息并构建返回数据
	var result []map[string]interface{}
	for _, summary := range summaries {
		userInfo, err := chatService.FetchUserDetails(summary.SenderID)
		if err != nil {
			fmt.Printf("failed to fetch user details for sender ID %d: %v\n", summary.SenderID, err)
			continue
		}

		// 构建消息信息并将其序列化为 JSON 字符串
		messageData := map[string]interface{}{
			"sender_id": summary.SenderID,
			"content":   summary.Content,
			"timestamp": summary.Timestamp.Unix(), // 转换为 UNIX 时间戳
		}

		messageJSON, err := json.Marshal(messageData)
		if err != nil {
			fmt.Printf("failed to marshal message data for sender ID %d: %v\n", summary.SenderID, err)
			continue
		}

		// 构建符合要求的返回格式，增加 unread_count 字段
		result = append(result, map[string]interface{}{
			"user": map[string]interface{}{
				"id":       userInfo["id"],
				"username": userInfo["username"],
				"nickname": userInfo["nickname"],
				"avatar":   userInfo["avatar"],
				"phone":    userInfo["phone"],
				"research": userInfo["research"],
				"is_admin": userInfo["is_admin"],
			},
			"message":      string(messageJSON), // 以 JSON 字符串格式存储消息
			"unread_count": summary.UnreadCount, // 未读消息数
		})
	}

	return result, nil
}

// 更新消息为已读
func (chatService *ChatService) MarkMessagesAsRead(senderID, receiverID int) error {
	if senderID >= 1000000 {
		senderID = senderID - 1000000 + 1
	}
	return global.GVA_DB.Model(&chat.ChatMessage{}).
		Where("sender_id = ? AND receiver_id = ? AND is_read = ?", senderID, receiverID, false).
		Update("is_read", true).Error
}

// FetchUserDetails 获取指定用户的完整信息，返回 map 格式
func (chatService *ChatService) FetchUserDetails(receiverID int) (map[string]interface{}, error) {
	fmt.Printf("receiverID: %d\n", receiverID)
	userData := make(map[string]interface{})
	if receiverID != 1 {
		var userInfo customer.CusUser
		// 查询数据库，获取指定 userID 的用户信息
		if err := global.GVA_DB.Where("id = ?", receiverID).First(&userInfo).Error; err != nil {
			return nil, fmt.Errorf("failed to get user info from database: %w", err)
		}
		// 构造返回的用户信息 map
		userData = map[string]interface{}{
			"id":       userInfo.ID,
			"username": userInfo.Username,
			"nickname": userInfo.Nickname,
			"avatar":   userInfo.Avatar,
			"phone":    userInfo.Phone,
			"research": userInfo.Research,
			"is_admin": false,
		}
	} else {
		var userInfo system.SysUser

		// 查询数据库，获取指定 userID 的用户信息
		if err := global.GVA_DB.Where("id = ?", receiverID).First(&userInfo).Error; err != nil {
			return nil, fmt.Errorf("failed to get user info from database: %w", err)
		}

		// 构造返回的用户信息 map
		userData = map[string]interface{}{
			"id":       userInfo.ID,
			"username": userInfo.Username,
			"is_admin": true,
		}
	}

	return userData, nil
}
